package com.gimi.cloud.bbp.manage.controller.app;

import java.io.InputStream;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.support.StandardMultipartHttpServletRequest;

import com.gimi.cloud.bbp.common.enums.ResponseCodeEnum;
import com.gimi.cloud.bbp.common.exception.MsgException;
import com.gimi.cloud.bbp.common.utils.Page;
import com.gimi.cloud.bbp.common.utils.UUIDUtil;
import com.gimi.cloud.bbp.common.utils.oss.AliOSSUtil;
import com.gimi.cloud.bbp.common.utils.reqhead.Response;
import com.gimi.cloud.bbp.dto.app.AdDTO;
import com.gimi.cloud.bbp.entity.app.AdEntity;
import com.gimi.cloud.bbp.entity.app.ColumnEntity;
import com.gimi.cloud.bbp.manage.service.app.AdService;
import com.gimi.cloud.bbp.manage.service.app.ColumnService;

/**
 * @auther loongs
 * @date 2017/12/27  15:27
 */
@RestController
@RequestMapping(value = "ad")
public class AdController {
    private static Logger logger = LoggerFactory.getLogger(AdController.class);

    private AdService adService;
    private ColumnService columnService;
    @Autowired
    public AdController(AdService adService,ColumnService columnService) {
        this.adService = adService;
        this.columnService=columnService;
    }

    @RequestMapping(value = "/getAdList")
    public Response getAdList(@RequestBody AdDTO adDTO, HttpServletResponse response) {
        logger.info("获得广告列表（分页），入参："+adDTO);
        Response resp = new Response();
        Page<AdDTO> list=adService.getAdList(adDTO);
        resp.setRes_data(list);
        resp.setResponseCode(ResponseCodeEnum.SUCCESSED);
        return resp;
    }

    @RequestMapping(value = "/addAd")
    public Response addAd(@RequestBody AdDTO adDTO, HttpServletResponse response) {
        logger.info("添加广告，入参："+adDTO);
        Response resp = new Response();
        boolean result=adService.addAd(adDTO);
        if(result){
            resp.setResponseCode(ResponseCodeEnum.SUCCESSED);
        }else{
            resp.setResponseCode(ResponseCodeEnum.ADD_AD_FAIL);
        }
        return resp;
    }

    @RequestMapping(value = "/editAd")
    public Response editAd(@RequestBody AdDTO adDTO, HttpServletResponse response) {
        logger.info("编辑广告，入参："+adDTO);
        Response resp = new Response();
        boolean result=adService.editAd(adDTO);
        if(result){
            resp.setResponseCode(ResponseCodeEnum.SUCCESSED);
        }else{
            resp.setResponseCode(ResponseCodeEnum.UPDATE_AD_FAIL);
        }
        return resp;
    }

    @RequestMapping(value = "/gotoEditAd")
    public Response gotoEditAd(@RequestBody AdDTO adDTO, HttpServletResponse response) {
        logger.info("转跳到编辑广告界面，入参："+adDTO);
        Response resp = new Response();
        AdEntity adEntity=adService.gotoEditAd(adDTO);
        resp.setRes_data(adEntity);
        resp.setResponseCode(ResponseCodeEnum.SUCCESSED);
        return resp;
    }

    @RequestMapping(value = "/gotoAddAd")
    public Response gotoAddAd(@RequestBody AdDTO adDTO, HttpServletResponse response) {
        logger.info("转跳到编辑广告页面（查询出所有的栏目对象），入参："+adDTO);
        Response resp = new Response();
        List<ColumnEntity> columnList=columnService.selectAll();
        resp.setRes_data(columnList);
        resp.setResponseCode(ResponseCodeEnum.SUCCESSED);
        return resp;
    }

    @RequestMapping(value = "/deleteAd")
    public Response deleteAd(@RequestBody AdDTO adDTO, HttpServletResponse response) throws MsgException {
        logger.info("删除广告，入参："+adDTO);
        Response resp = new Response();
        boolean result=adService.deleteAd(adDTO);
        if(result){
            resp.setResponseCode(ResponseCodeEnum.SUCCESSED);
        }else{
            resp.setResponseCode(ResponseCodeEnum.DELETE_AD_FAIL);
        }
        return resp;
    }

    @RequestMapping(value = "/underAd")
    public Response underAd(@RequestBody AdDTO adDTO, HttpServletResponse response) throws MsgException {
        logger.info("撤下广告，入参："+adDTO);
        Response resp = new Response();
        boolean result=adService.underAd(adDTO);
        if(result){
            resp.setResponseCode(ResponseCodeEnum.SUCCESSED);
        }else{
            resp.setResponseCode(ResponseCodeEnum.UNDER_AD_FAIL);
        }
        return resp;
    }

    @RequestMapping(value = "/publishAd")
    public Response publishAd(@RequestBody AdDTO adDTO, HttpServletResponse response) throws MsgException {
        logger.info("发布广告，入参："+adDTO);
        Response resp = new Response();
        boolean result=adService.publishAd(adDTO);
        if(result){
            resp.setResponseCode(ResponseCodeEnum.SUCCESSED);
        }else{
            resp.setResponseCode(ResponseCodeEnum.PUBLISH_AD_FAIL);
        }
        return resp;
    }




    @RequestMapping(value = "/uploadAdFile")
    public Response uploadAdFile(HttpServletRequest request, HttpServletResponse response) throws Exception {
        String url = "";
        StandardMultipartHttpServletRequest multipartHttpServletRequest = (StandardMultipartHttpServletRequest) request;
        MultiValueMap multipartFiles = multipartHttpServletRequest.getMultiFileMap();
        for(Object entry : multipartFiles.entrySet()){
            LinkedList<MultipartFile> lists = ((Map.Entry<String, LinkedList<MultipartFile>>) entry).getValue();
            for(MultipartFile file : lists){
                InputStream is = file.getInputStream();
                String uuId = UUIDUtil.get32UUID();
                String dirPath = "ad";
                String[] originalFilenames = file.getOriginalFilename().split("\\.");
                String fileName = uuId + "." + originalFilenames[originalFilenames.length-1];
                //测试上传时间
                long startTime1=System.currentTimeMillis();
                String result = AliOSSUtil.uploadFile(is,dirPath,fileName);
                long endTime1=System.currentTimeMillis();
                logger.info("上传ad图片到OSS，所用时间： "+(endTime1-startTime1)+"ms");

                long startTime2=System.currentTimeMillis();
                String tempUrl = AliOSSUtil.getFileUrl(result,new Date(System.currentTimeMillis() + 1000 * 60 * 60 * 24 * 365 * 100));
                long endTime2=System.currentTimeMillis();
                logger.info("获得ad图片的url路径，所用时间： "+(endTime2-startTime2)+"ms");

                url += ","+tempUrl;
                System.out.println("==========>上传结果：" + url);
            }
        }

        Response resp = new Response();
        Map<String,String> data = new HashMap<>();
        data.put("url",url.equals("")?url:url.substring(1));
        resp.setRes_data(data);
        resp.setResponseCode(ResponseCodeEnum.SUCCESSED);
        return resp;
    }
}
